<template>
  <div>
    <!--方法2：node-key="id"， :default-checked-keys="permIds" -->
    <el-tree
      ref="tree"
      show-checkbox
      check-strictly
      default-expand-all
      node-key="id"

      :data="list"
      :props="{label:'name',children:'children'}"
    />
    <el-row type="flex" justify="end" height="60">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button type="info" @click="$emit('close')">取消</el-button>
    </el-row>

  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { transDataToTreeData } from '@/utils'// 导入树形结构函数
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [] // 权限站点列表
      // permIds: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 给角色分配权限
    async hSubmit() {
      // 发送请求
      try {
        const permIds = this.$refs.tree.getCheckedKeys()
        console.log('permIds', permIds) // 得到选中的权限节点permIds
        // 给角色分配权限
        const res = await assignPerm({ id: this.roleId, permIds: permIds })
        console.log('给角色分配权限res', res)
        // this.getRoleDetail() // 重新获取角色详情
        this.$emit('close')
      } catch (error) {
        console.log(error)
      }
    },
    // 获得权限站点列表
    async loadPermissionList() {
      try {
        // 获得权限站点列表
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        this.list = transDataToTreeData(res.data) // 将数据转换成树形结构数据
        // 获取角色详情
        const info = await getRoleDetail(this.roleId)
        console.log('获取角色详情info', info)
        this.$refs.tree.setCheckedKeys(info.data.permIds)// 方法1：把角色有的权限回填
        // this.permIds = info.data.permIds //方法2： 把角色有的权限回填
      } catch (err) {
        console.log('getPermissionList', err)
      }
    }
  }
}
</script>

<style>

</style>
